<template>
  <!-- 编辑章节 -->
  <el-dialog :visible.sync="localVisible" :title="title" width="500px" @close="handleClose"
    :close-on-click-modal="false" append-to-body>
    <div class="dialog-content">
      <!-- 树结构 -->
      <div class="chapter-container">
        <el-tree :data="chapters" node-key="id" default-expand-all :expand-on-click-node="false">
          <span slot-scope="{ node, data }" :class="['custom-tree-node', { editing: data.editing }]">
            <span v-if="!data.editing">{{ node.label }}</span>
            <el-input v-else v-model="data.label" placeholder="请输入章节名称"></el-input>
            <span>
              <!-- 控制只有 level=0 的节点才能添加子节点 -->
              <el-button v-if="data.level === 0" type="text" size="mini" @click="() => append(data)">
                添加子节
              </el-button>
              <el-button v-if="!data.editing" type="text" size="mini" @click="() => edit(data)">编辑</el-button>
              <el-button v-if="!data.editing" type="text" size="mini" @click="() => remove(node, data)">删除</el-button>
              <el-button v-if="data.editing" type="text" size="mini" @click="() => saveEdit(data)">保存</el-button>
              <el-button v-if="data.editing" type="text" size="mini" @click="() => cancelEdit(data)">取消</el-button>
            </span>
          </span>
        </el-tree>
      </div>

      <!-- 居中的按钮 -->
      <div class="button-wrapper">
        <el-button class="import-button" type="primary" @click="addTopLevelNode">添加章节</el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import { addSctktChapter, updateSctktChapter, delSctktChapter } from '@/api/sctkChapter'
export default {
  name: 'UpdateChapter',
  props: {
    showDialog: {
      type: Boolean,
      default: false,
      required: true
    },
    title: {
      type: String,
      default: '编辑章节'
    },
    fk_t_sctk_id: {
      type: Number,
      required: true
    },
    chapters: {
      type: Array,
      required: true
    }
  },
  data() {
    return {
      localVisible: this.showDialog,
    };
  },
  watch: {
    showDialog(newVal) {
      this.localVisible = newVal;
    },
    localVisible(newVal) {
      if (newVal !== this.showDialog) {
        this.$emit('update:showDialog', newVal);
      }
    }
  },
  methods: {
    handleClose() {
      this.localVisible = false;
    },
    async append(data) {
      const MAX_LEVEL = 2;

      const currentLevel = data.level || 0;

      if (currentLevel >= MAX_LEVEL - 1) {
        this.$message.warning('最多只能创建两层结构');
        return;
      }

      const newChild = {
        // id: this.id++,
        label: '新章节',
        level: currentLevel + 1,
        editing: false, // 明确加上 editing 字段
        isTemp: true
      };

      if (!data.children) {
        this.$set(data, 'children', []);
      }
      data.children.push(newChild);

      const addForm = {
        fk_t_sctk_id: this.fk_t_sctk_id,
        name: newChild.label,
        parent_id: data.id,
      }
      try {
        const res = await addSctktChapter(addForm);

        // 成功后更新 ID 和状态
        newChild.id = res.data;
        newChild.editing = false;
        newChild.isTemp = false;
        // 更新完成后通知上级组件刷新数据

        this.$emit('chapter-updated');
        // this.getChapters()

        // this.$message.success('新增章节成功');
      } catch (error) {
        // this.$message.error('新增章节失败');
        data.children.pop(); // 回滚
      }
    },
    async remove(node, data) {
      this.$confirm('删除后，可在回收站恢复', '提示', {
        type: 'warning'
      })
        .then(async () => {
          await delSctktChapter({ id: data.id });
          const parent = node.parent;
          const children = parent.data.children || parent.data;
          const index = children.findIndex(d => d.id === data.id);
          children.splice(index, 1);
        })
        .catch(action => {
          if (action === 'cancel') {
            // console.log('用户点击了取消');
          } else {
            // console.error('删除失败:', action);
          }
        });
    },
    edit(data) {
      // data.editing = true; // 开启编辑模式
      this.$set(data, 'editing', true); // 使用 $set 触发响应式更新
    },
    async saveEdit(data) {
      // data.editing = false; // 关闭编辑模式
      const updateForm = { name: data.label, id: data.id };
      await updateSctktChapter(updateForm);
      this.$set(data, 'editing', false);

      this.$message.success('保存成功');
    },
    cancelEdit(data) {
      this.$set(data, 'editing', false);
      // data.editing = false; // 取消编辑模式
    },
    async addTopLevelNode() {
      const newTopNode = {
        label: '新章节',
        level: 0,
        editing: true,
        isTemp: true
      };
      this.chapters.push(newTopNode);
      try {
        const res = await addSctktChapter({
          fk_t_sctk_id: this.fk_t_sctk_id,
          name: newTopNode.label,
          parent_id: 0
        });

        newTopNode.id = res.id;
        newTopNode.editing = false;
        newTopNode.isTemp = false;
        this.$emit('chapter-updated');
        // this.$message.success('新增顶级章节成功');
      } catch (error) {
        // this.$message.error('新增顶级章节失败');
        this.chapters.pop();
      }
    }
  }
};
</script>

<style scoped>
.dialog-content {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.chapter-container {
  flex: 1;
  overflow-y: auto;
  padding-bottom: 10px;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

.button-wrapper {
  text-align: center;
  margin-top: 10px;
}

/* 新增样式 */
.el-input {
  width: 200px;
  /* 调整输入框宽度 */
}

.el-button {
  margin-left: 5px;
  /* 调整按钮间距 */
}

.el-tree-node__content {
  width: 100%;
  /* 让节点内容占据整个容器宽度 */
}

/* 在编辑模式下进一步调整节点内容的布局 */
.custom-tree-node.editing .el-tree-node__content {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

/* 确保输入框和按钮在同一行显示 */
.custom-tree-node.editing .el-input {
  width: calc(100% - 200px);
  /* 根据需要调整宽度 */
  margin-right: 10px;
  /* 给右侧按钮留出空间 */
}

.edit-container {
  display: flex;
  align-items: center;
  width: 100%;
}

.button-group {
  display: flex;
  align-items: center;
}

.button-group .el-button {
  margin-left: 5px;
  /* 调整按钮间距 */
}
</style>